/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 2 -*- */
/**
* @file debug.cpp
* 
* Library for easy log and debugging.
* 
* @author Miguel Ángel Vílchez López 2010 <sacra@openmatica.es>
*
* Codigo is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* 
* Codigo is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License along
* with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "debug.hpp"

#ifndef _MOKARDU_DEBUG_CPP_
#define _MOKARDU_DEBUG_CPP_

CMDebug::CMDebug(bool debug=false,const char* filename="")
{
	this->filename=(char*)malloc((strlen(filename)+1)*sizeof(char));
	this->bdebug=debug;
	strcpy(this->filename,filename);
}

CMDebug::~CMDebug()
{
	free(this->filename);
}

void CMDebug::getTime(char *thetime)
{
	time_t mytime;
	struct tm *mytm;
	mytime=time(NULL);
	mytm=localtime(&mytime);

	strftime(thetime,22,"%d %b %Y %H:%M:%S",mytm);
}

void CMDebug::errorLog(const char *error,const char *errorfile,const char *errorfunction,int errorline)
{
	FILE * fp=fopen(this->filename,"a");
	char *thetime=(char*)malloc(100 * sizeof(char));
	getTime(thetime);

	fprintf(fp, "%s : Launch file '%s' on function '%s' at line '%d' this error: '%s'\n",thetime,errorfile,errorfunction,errorline,error);

	fclose(fp);
	free(thetime);
}

void CMDebug::errorShow(const char* error,const char* errorfile,const char* errorfunction,int errorline)
{
	char *thetime=(char*)malloc(100 * sizeof(char));	
	this->getTime(thetime);

	fprintf(stderr,"%s : Launch file '%s' on function '%s' at line '%d' this error: '%s'\n",thetime,errorfile,errorfunction,errorline,error);

	free(thetime);
}

void CMDebug::debugLog(const char* debug)
{
	if(this->bdebug == true)
	{
		FILE * fp=fopen(this->filename,"a");
		char *thetime=(char*)malloc(100 * sizeof(char));
		getTime(thetime);

		fprintf(fp, "%s\n",debug);

		fclose(fp);
		free(thetime);
	}
}

void CMDebug::debugShow(const char* debug)
{
	if(this->bdebug == true)
	{
		char *thetime=(char*)malloc(100 * sizeof(char));	
		this->getTime(thetime);
	
		fprintf(stderr,"%s\n",debug);

		free(thetime);
	}
}

void CMDebug::error(const char* error,const char* errorfile,const char* errorfunction,int errorline)
{
	if(strlen(this->filename)>0)
	{
		this->errorLog(error,errorfile,errorfunction,errorline);
	}
	this->errorShow(error,errorfile,errorfunction,errorline);
}

void CMDebug::debug(const char* debug)
{
	if(this->bdebug==true)
	{
		if(strlen(this->filename)>0)
		{	this->debugLog(debug); }
		this->debugShow(debug);
	}
}

#endif // _MOKARDU_DEBUG_CPP_
